package com.serkol.ams.utils;

import com.serkol.ams.module.sys.entity.SysRole;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Set;

@Data
@Component
public class JwtUtils {
    /**
     * token过期时间
     */
    public static final long EXPIRE = 18000000;  //过期时间30分钟(单位毫秒)

    /**
     * 秘钥
     */
    public static final String SECRET = "NllmZHptNVVrNG9RRUs3NllmZHptNVVrNG9RRUs3NllmZHptNVVrNG9RRUs3NllmZHptNVVrNG9RRUs3NllmZHptNVVrNG9RRUs3NllmZHptNVVrNG9RRUs3NllmZHptNVVrNG9RRUs3Nl";

    /**
     * 生成token字符串的方法
     *
     * @param id
     * @param username
     * @return
     */
/*    public static String getJwtToken(String id, String username) {
        String jwtToken = Jwts.builder().setHeaderParam("typ", "JWT").setHeaderParam("alg", "HS256")
                .setSubject("user").setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //设置token主体部分 ，存储用户信息
                .claim("id", id)
                .claim("username", username)
                .signWith(HS256, SECRET).compact();
        return jwtToken;
    }*/
    public static String getJwtToken(String id, String username) {
    //    SecretKey secretKey = Keys.secretKeyFor(HS256);
//        byte[] secretKeyBytes = Keys.secretKeyFor(SignatureAlgorithm.HS256);
//    String secret = Base64.getEncoder().encodeToString(secretKeyBytes);

        return Jwts.builder().setHeaderParam("typ", "JWT")
            .setHeaderParam("alg", "HS256").setSubject(username)
            .setIssuedAt(new Date())
            .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
            //璁剧疆token涓讳綋閮ㄥ垎 锛屽瓨鍌ㄧ敤鎴蜂俊鎭�
            .claim("id", id)
            .claim("username", username)
            .signWith(getSecretKey(), SignatureAlgorithm.HS256).compact();
}
  public static String generateToken(String username, Set<SysRole> authorities) {
        return Jwts.builder().subject(username)
                .claim("roles", authorities)//can also set a map
                .issuedAt(new Date(System.currentTimeMillis()))
                .expiration(new Date(System.currentTimeMillis() + EXPIRE * 1000))
                .issuer("https://www.devglan.com")
                .signWith(getSecretKey(), SignatureAlgorithm.HS512)
                .compact();
    }

    private static SecretKey getSecretKey() {
        byte[] keyBytes = Decoders.BASE64.decode(SECRET);
        return Keys.hmacShaKeyFor(keyBytes);
    }
    /**
     * 判断token是否存在与有效
     *
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(SECRET).build().parseClaimsJws(jwtToken);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     *
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("Authorization");
            if (StringUtils.isEmpty(jwtToken)) {
                return false;
            }
            Jwts.parser().setSigningKey(SECRET).build().parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token字符串获取id
     *
     * @param request
     * @return
     */
    public static String getUserIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("Authorization");
        if (StringUtils.isEmpty(jwtToken)) {
            return "";
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET).build().parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("id");
    }

    /**
     * 验证jwt
     */
    public static Claims verifyJwt(String token) {
        Claims claims;
        try {
            //得到DefaultJwtParser
            claims = Jwts.parser()
                    //设置签名的秘钥
                    .setSigningKey(SECRET)
                    .build().parseClaimsJws(token).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            claims = null;
        }//设置需要解析的jwt
        return claims;
    }
}
